package com.meihua.shellapp.activity.set;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.meihua.shellapp.R;
import com.meihua.shellapp.base.BaseActivity;
import com.meihua.shellapp.base.BaseBean;
import com.meihua.shellapp.base.MyApplication;
import com.meihua.shellapp.common.NetHelper;
import com.meihua.shellapp.utils.MyStringCallBack;
import com.meihua.shellapp.utils.SharedPreferencesUtil;
import com.meihua.shellapp.utils.ToastUtils;
import com.meihua.shellapp.utils.URL;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

import static com.meihua.shellapp.R.id.tv_get_code;

/**
 * 更换手机号
 */

public class ChangePhoneActivity extends BaseActivity {

    @Bind(R.id.tv_top_left)
    TextView tvTopLeft;
    @Bind(R.id.iv_top_left)
    ImageView ivTopLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;

    @Bind(tv_get_code)
    TextView txtCode;

    @Bind(R.id.tv_finish)
    TextView edtTxtChangePhone;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.et_verification_code)
    EditText etVerificationCode;
    private int time;//倒计时时间

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what >= 0) {
                txtCode.setBackgroundResource(R.drawable.btn_backgroud_gary_6);
                txtCode.setText(msg.what + "");
            } else {
                txtCode.setBackgroundResource(R.drawable.btn_backgroud_round_6);
                txtCode.setText("获取验证码");
            }
        }
    };
    private String phone;

    @Override
    public int getLayoutId() {
        return R.layout.activity_change_phone;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ivTopLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("更换手机号码");
        tvTitle.setVisibility(View.VISIBLE);
        ivTopLeft.setOnClickListener(this);
        phone = getIntent().getStringExtra("phone");
    }

    /**
     * 加载服务器数据
     */
    private void loadData() {
        Map<String, String> params = new HashMap() {{
            put("phone", phone);
            put("newPhone", etPhone.getText().toString());
            put("code", etVerificationCode.getText().toString());
            put("type", 4 + "");
            put("mid", MyApplication.getInstance().getMId());
        }};
        NetHelper.post(URL.getUrl().CHECKPHONE, params, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(Response<String> response) {
                JSONObject obj = null;
                try {
                    obj = new JSONObject(response.body());
                    if (obj.getInt("code") == 1) {
                        Toast.makeText(ChangePhoneActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        MyApplication.getInstance().bean.setPhone(etPhone.getText().toString());
                        SharedPreferencesUtil.getInstance().saveString(mContext, "phone", etPhone.getText().toString());
                        finish();
                    } else {
                        Toast.makeText(ChangePhoneActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, true);
    }

    @OnClick({R.id.iv_top_left, tv_get_code, R.id.tv_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top_left:
                finish();
                break;
            case tv_get_code:
                /*发送验证码*/
                sendCode();
                break;
            case R.id.tv_finish:
                loadData();
                break;
        }
    }

    private void sendCode() {
        OkGo.<String>post(URL.getUrl().SENDCODE)
                .params("phone", etPhone.getText().toString())
                .params("type", "4")
                .execute(new MyStringCallBack<BaseBean>(edtTxtChangePhone) {
                    @Override
                    public void onSuccessData(BaseBean baseBean) {
                        super.onSuccessData(baseBean);
                        if (baseBean.getCode() == 1) {
                            countDown(60);//倒计时
                        }
                        ToastUtils.getInstance().showToast(baseBean.getMsg());
                    }
                });
    }

    /**
     * 倒计时
     *
     * @param timetemp 时间(s)
     */
    private void countDown(int timetemp) {
        time = timetemp;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (time < 0) {
                    return;
                }
                time--;
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(time);
                    run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }

            }
        }).start();
    }
}
